<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addCate">添加分类</el-button>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <table-tree
        class="treeTbale"
        :data="catelist"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        index-text="#"
        border
      >
        <!-- 是否有效 -->
        <template slot="isok" slot-scope="scope">
          <i class="el-icon-success" v-if="scope.row.cat_deleted === false" style="color:#35bdb6"></i>
          <i class="el-icon-error" v-else style="color:red"></i>
        </template>
        <!-- 排序 -->
        <template slot="order" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level === 0" size="mini">一级</el-tag>
          <el-tag v-else-if="scope.row.cat_level ===1" type="success" size="mini">二级</el-tag>
          <el-tag v-else type="warning" size="mini">三级</el-tag>
        </template>
        <!-- 操作按钮 -->
        <template slot="opt" slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="bianji(scope.row.cat_id)"
          >编辑</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini"  @click="removeCateById(scope.row.cat_id)" >删除</el-button>
        </template>
      </table-tree>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加分类对话框 -->
    <el-dialog title="添加分类" :visible.sync="addCatedialogVisible" width="50%" @close="Cateclose">
      <!-- 添加分类的表单 -->
      <el-form
        :model="addCateForm"
        :rules="addCateRules"
        ref="addCateRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <!-- options指定数据源 -->
          <!-- props指定配置对象 -->
          <!-- :props="{ expandTrigger: 'hover' }" -->
          <el-cascader
            v-model="cascadervalue"
            :options="parentList"
            :props="props"
            @change="handleChange"
            clearable
            change-on-select
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCatedialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="baocuntijiao">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑并提交对话框 -->
    <el-dialog title="编辑" :visible.sync="bianjidialog" width="50%" @close="bianjiclose">
      <el-form
        :model="editForm"
        :rules="bianjiRules"
        ref="bianjiRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="ID" prop="cat_id">
          <el-input v-model="editForm.cat_id" disabled></el-input>
        </el-form-item>
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="bianjidialog = false">取 消</el-button>
        <el-button type="primary" @click="biaotiInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 分页
      queryInfo: {
        type: 3,
        // 当前页数
        pagenum: 1,
        // 当前每页显示多少数据
        pagesize: 5
      },
      //数据列表
      catelist: [],
      total: 0,
      columns: [
        {
          label: "分类名称",
          prop: "cat_name"
        },
        {
          label: "是否有效",
          //将定义成模板列
          type: "template",
          //   设置模板列的名称
          template: "isok"
        },
        {
          label: "是否有效",
          type: "template",
          template: "order"
        },
        {
          label: "操作",
          type: "template",
          template: "opt"
        }
      ],
      // 添加分类的对框框的显示与隐藏
      addCatedialogVisible: false,
      addCateForm: {
        cat_id: "",
        cat_pid: "",
        cat_name: "",
        cat_level: ""
      },
      //添加分类验证规则
      addCateRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
          { trigger: "blur" }
        ]
      },
      // 编辑分类的验证规则
      bianjiRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
          { trigger: "blur" }
        ]
      },
      // 父级分类的数据列表
      parentList: [],
      props: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        expandTrigger: "hover"
      },
      //绑定的级联选择器ID值
      cascadervalue: [],
      // 编辑分类对话框显示与隐藏
      bianjidialog: false,
      // 修改表单的验证规则对象

      // 查询信息对象
      editForm: {
        cat_name: ""
      }
    };
  },
  created() {
    this.getcateList();
  },
  methods: {
    //获取列表数据
    async getcateList() {
      const { data: res } = await this.$http.get("categories", {
        params: this.queryInfo
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取列表失败");
      }
      //   console.log(res.data);
      this.catelist = res.data.result;
      this.total = res.data.total;
    },
    // 监听pagenum
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getcateList();
    },
    // 监听pagesize
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getcateList();
    },
    addCate() {
      this.getParentList();
      this.addCatedialogVisible = true;
    },
    // 获取父级分类的数据列表
    async getParentList() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: 2 }
      });
      if (res.meta.status !== 200) {
        this.$message.error("获取数据列表失败");
      }
      // 数据赋值到列表
      this.parentList = res.data;
      console.log(this.parentList);
    },
    // 当选择项数据改变时会触发此函数
    handleChange() {
      // console.log(this.cascadervalue)
      // 如果cascadervalue数组中length大于0，证明选中父级分类
      // 返之没有选中任何父级分类
      if (this.cascadervalue.length > 0) {
        // 父级分类的ID
        this.addCateForm.cat_pid = this.cascadervalue[
          this.cascadervalue.length - 1
        ];
        //分类等级赋值
        this.addCateForm.cat_level = this.cascadervalue.length;
        return;
      } else {
        // 父级分类的ID
        this.addCateForm.cat_pid = 0;
        //分类等级赋值
        this.addCateForm.cat_level = 0;
      }
    },
    //点击按钮添加新分类
    baocuntijiao() {
      this.$refs.addCateRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.post("categories/", {
          cat_name: this.addCateForm.cat_name,
          cat_pid: this.addCateForm.cat_pid,
          cat_level: this.addCateForm.cat_level
        });
        if (res.meta.status !== 201) {
          return this.$message.error("添加分类失败");
        }
        //关闭对话框
        this.addCatedialogVisible = false;
        //刷新列表
        this.getcateList();
        // 更新用户成功
        this.$message.success("添加分类成功");
      });
    },
    // 监听对话框的重置操作
    Cateclose() {
      this.$refs.addCateRef.resetFields();
      this.cascadervalue = [];
      this.addCateForm.cat_level = 0;
      this.addCateForm.cat_pid = 0;
    },
    // 编辑并提交
    async bianji(id) {
      console.log(id);
      // 编辑对话框的显示与隐藏
      // this.bianjidialog = true;
      const { data: res } = await this.$http.get("categories/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error("查询用户信息失败");
      }
      this.editForm = res.data;
      this.bianjidialog = true;
    },
    //关闭对话框的重置按钮
    bianjiclose() {
      this.$refs.bianjiRef.resetFields();
    },
    //提交保存
    biaotiInfo() {
      this.$refs.bianjiRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          "categories/" + this.editForm.cat_id,
          this.editForm
        );
        if (res.meta.status !== 200) {
          return this.$message.error("修改用户失败");
        }
        //关闭对话框
        this.bianjidialog = false;
        //刷新列表
        this.getcateList();
        // 更新用户成功
        this.$message.success("更新分类列表成功");
      });
    },
    //删除分类
    async removeCateById(id) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该分类, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(error => {
        return error;
      });
      //如果用户确认删除则返回字符串confirm
      //如果用户取消删除，则返回字符串cancel
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }
      const { data: res } = await this.$http.delete("categories/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error("删除分类失败");
      }
      this.$message.success("删除分类成功");
      //更新列表
      this.getcateList();
    }
  }
};
</script>

<style lang="less" scoped>
.treeTbale {
  margin-top: 15px;
}
// .el-cascader{
//   width: 100%;
// }
</style>